package com.hmdp.service.impl;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.filter.CharacterEncodingFilter;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CharacterEncodingFilter characterEncodingFilter;
    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        Shop shop = cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);

        return Result.ok(shop);
    }

    // 线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public Result queryLogicExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 查询Redis
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isBlank(shopJson)) {
            return Result.fail("商品不存在");
        }
        // 将嵌套Json转化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 因为是redisData中data是Object类型, 工具类无法判断具体类型,就转化为了JSONObject
        JSONObject jsonObject = (JSONObject) redisData.getData();
        Shop shop = jsonObject.toBean(Shop.class);

        if ( expireTime.isAfter(LocalDateTime.now()) ) {
            // 没有过期
            return Result.ok(shop);
        }

        // 互斥锁1. 获取锁
        String mutexKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(mutexKey);

        if (isLock) {
            // 过期了, 成功获取锁,开启子线程重建缓存
            // 需要doublecheck 因为你这时候获取到锁 也有一种可能是其他线程做完了重建释放了锁
            // 查询Redis
            shopJson = stringRedisTemplate.opsForValue().get(key);
            redisData = JSONUtil.toBean(shopJson, RedisData.class);
            expireTime = redisData.getExpireTime();
            if (!expireTime.isAfter(LocalDateTime.now())) {
                // 开启子线程
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    this.saveShop2Redis(id, 20L);
                    // 不要忘记释放锁
                    unlock(mutexKey);
                });
            }
        }

        return Result.ok(shop);
    }

    public Result queryMutex(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 查询Redis
        String s = stringRedisTemplate.opsForValue().get(key);

        Shop shop = null;

        if (StrUtil.isNotBlank(s)) {
            shop = JSONUtil.toBean(s, Shop.class);
            return Result.ok(shop);
        }
        // s为空,且s!=null那么就是空字符，即为不存在的id
        // s==null表示没有命中, s==""表示为空即命中了空
        if ( s != null ) {
            return Result.fail("店铺不存在");
        }
        // 互斥锁1. 获取锁
        String mutexKey = RedisConstants.LOCK_SHOP_KEY + id;
        try {
            boolean flag = tryLock(mutexKey);
            if (!flag) {
                // 没拿到锁就睡眠后重新尝试
                Thread.sleep(50);
                return queryMutex(id);
            }
            // 获取到锁就查询
            shop = getById(id);
            if (shop == null) {
                // 将空值写入到redis
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);    // 过期时间更短
                return Result.fail("店铺不存在");
            }
            String jsonStr = JSONUtil.toJsonStr(shop);
            // 存储到redis
            stringRedisTemplate.opsForValue().set(key, jsonStr, 30L, TimeUnit.MINUTES);     // 设置超时时间，做兜底方案
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            unlock(mutexKey);
        }
        return Result.ok(shop);
    }

    @Override
    @Transactional      // 注意开启事务
    public Result updateShop(Shop shop) {
        // 判断id是否存在
        if (shop.getId() == null) {
            return Result.fail("店铺不存在");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        String key = RedisConstants.CACHE_SHOP_KEY + shop.getId();
        stringRedisTemplate.delete(key);
        return Result.ok();

    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if (x==null || y==null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 计算分页参数
        int from = (current-1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        // 查询redis
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key, GeoReference.fromCoordinate(x, y), new Distance(5000), RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results==null) {
            return Result.ok();
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        // 截取from到end的部分
        if (list.size() <= from) {
            return Result.ok();     // 判断是否最后一页，跳过后直接空了
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(e->{       // redis分页只能从0开始到end结束，所有查出来需要手动截取from
            String shopIdStr = e.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = e.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }

    public void saveShop2Redis(Long id, Long expireSeconds) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(redisData));
    }

    // 获取锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);   // 直接转化为bool自动拆箱可能造成空指针异常
        return BooleanUtil.isTrue(flag);
    }
    // 释放锁
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
